package org.oexam.ostudy.serv;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.oexam.ostudy.facade.LoginPage;
import org.oexam.ostudy.facade.struct.LoggedUserDetails;

/**
 * Servlet implementation class Login
 */
@WebServlet(description = "To process login request", urlPatterns = { "/Login" })
public class Login extends HttpServlet {
	private static final long serialVersionUID = 1L;

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		

		String userName = request.getParameter("userName");
		String userPassword = request.getParameter("userPassword");

		if ((userName == "") || (userPassword == "")) {
			
			response.sendRedirect("LoginFailed.jsp");

		} else {
			LoginPage loginPage = new LoginPage();
			LoggedUserDetails loggedUserDetails = loginPage.authenticateUser(
					userName, userPassword);

			
			if (loggedUserDetails.isAuthenticated()) {
				
				request.getSession().setAttribute("userLoginDetails", loggedUserDetails);
				if(loggedUserDetails.getUserType()==0){
					response.sendRedirect("Administrators.jsp");
				}
				else if(loggedUserDetails.getUserType()==1){
					response.sendRedirect("Teacher.jsp");
				}
				else if(loggedUserDetails.getUserType()==2){
					response.sendRedirect("Student.jsp");
				}
				else {
					response.sendRedirect("LoginFailed.jsp");
				}
				
			} else {
				response.sendRedirect("LoginFailed.jsp");
			}

		}

	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

		response.sendRedirect("Login.jsp");
	}

}
